package com.bolt.support.query.toolkit;

import com.bolt.common.collection.IteratorUtil;
import com.bolt.common.convert.Convert;
import com.bolt.support.query.calculator.domain.PivotModel;
import com.bolt.support.query.calculator.domain.UnpivotModel;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ResultUtil {


    private static List<?> calculate(List<?> results, List<String> aliases, List<?> resultProcessors) {
        // 计算
        if (IteratorUtil.isNotEmpty(resultProcessors)) {
            Object processor;
            for (int i = 0; i < resultProcessors.size(); i++) {
                processor = resultProcessors.get(i);
                if (processor instanceof PivotModel) {
                    results = PivotResult.process((PivotModel) processor, results, aliases);
                } else if (processor instanceof UnpivotModel) {
                    results = UnpivotResult.process((UnpivotModel) processor, results, aliases);
                }
            }
        }
        return results;
    }

    public static List<?> getResultList(List<?> results, List<String> aliases, List<?> resultProcessors, Class<?> returnClass, Map<String, Field> accessFields) {
        results = calculate(results, aliases, resultProcessors);
        List<Object> rv = new ArrayList<>(results.size());
        for (Object o : results) {
            if (o != null) {
                if (BeanUtils.isSimpleProperty(returnClass)) {
                    rv.add(Convert.convert(returnClass, o));
                    continue;
                }
                if (!o.getClass().isArray()) {
                    o = new Object[]{o};
                }
                rv.add(JPAUtil.toBean((Object[]) o, returnClass, aliases, accessFields));
            } else {
                rv.add(null);
            }
        }
        return rv;
    }

    public static Object getSingleResult(Object result, List<String> aliases, Class<?> returnClass, Map<String, Field> accessFields) {
        if (result != null) {
            if (BeanUtils.isSimpleProperty(returnClass)) {
                return result;
            }
            if (!result.getClass().isArray()) {
                result = new Object[]{result};
            }
            return JPAUtil.toBean((Object[]) result, returnClass, aliases, accessFields);
        } else {
            return null;
        }
    }

}

